from django.db import models, connection
from django.utils import timezone
from .utils import generate_snowflake_id, get_order_table_name

class Appointment(models.Model):
    """预约信息模型"""
    APPOINTMENT_STATUS = (
        ('pending', '待确认'),
        ('confirmed', '已确认'),
        ('canceled', '已取消'),
        ('completed', '已完成'),
    )
    
    id = models.BigIntegerField(primary_key=True, editable=False)
    patient_id = models.IntegerField('患者ID')
    doctor_id = models.IntegerField('医生ID')
    doctor_name = models.CharField('医生姓名', max_length=50)
    doctor_title = models.CharField('医生职称', max_length=50)
    hospital_name = models.CharField('医院名称', max_length=100)
    hospital_address = models.CharField('医院地址', max_length=255)
    department = models.CharField('科室', max_length=50)
    appointment_date = models.DateField('预约日期')
    appointment_weekday = models.CharField('星期', max_length=10)
    time_slot = models.CharField('时间段', max_length=20)
    fee = models.CharField('费用', max_length=20)
    status = models.CharField('状态', max_length=20, choices=APPOINTMENT_STATUS, default='pending')
    created_at = models.DateTimeField('创建时间', auto_now_add=True)
    updated_at = models.DateTimeField('更新时间', auto_now=True)
    
    def save(self, *args, **kwargs):
        if not self.id:
            # 使用雪花算法生成ID
            self.id = generate_snowflake_id()
        super().save(*args, **kwargs)
    
    class Meta:
        db_table = 'reservation_appointment'
        verbose_name = '预约信息'
        verbose_name_plural = '预约信息'
        
    def __str__(self):
        return f"{self.patient_id}的{self.appointment_date}预约"


class OrderManager:
    """订单管理类 - 处理订单表的增删改查"""
    
    @staticmethod
    def create_order(patient_id, doctor_id, appointment_id, amount):
        """创建订单"""
        order_id = generate_snowflake_id()
        table_name = get_order_table_name(order_id)
        
        # 生成订单编号：时间戳+订单ID后6位
        order_number = f"{int(timezone.now().timestamp())}{str(order_id)[-6:]}"
        now = timezone.now().strftime('%Y-%m-%d %H:%M:%S')
        
        with connection.cursor() as cursor:
            cursor.execute(
                f"""INSERT INTO {table_name} 
                   (id, order_number, patient_id, doctor_id, appointment_id, 
                    amount, status, created_at, updated_at) 
                   VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s)""",
                [
                    order_id, 
                    order_number, 
                    patient_id, 
                    doctor_id,
                    appointment_id,
                    amount,
                    'pending',  # 初始状态为待支付
                    now,
                    now
                ]
            )
        
        return {
            'id': order_id,
            'order_number': order_number,
            'patient_id': patient_id,
            'doctor_id': doctor_id,
            'appointment_id': appointment_id,
            'amount': amount,
            'status': 'pending',
            'created_at': now
        }
    
    @staticmethod
    def get_order(order_id):
        """获取订单详情"""
        table_name = get_order_table_name(order_id)
        
        with connection.cursor() as cursor:
            cursor.execute(
                f"SELECT * FROM {table_name} WHERE id = %s",
                [order_id]
            )
            row = cursor.fetchone()
            
            if not row:
                return None
            
            # 列名和位置
            columns = ['id', 'order_number', 'patient_id', 'doctor_id', 
                      'appointment_id', 'amount', 'status', 'payment_method', 
                      'payment_time', 'created_at', 'updated_at']
            
            # 构建结果字典
            result = {}
            for i, column in enumerate(columns):
                if i < len(row):
                    result[column] = row[i]
                    
            return result
    
    @staticmethod
    def update_order_status(order_id, status, payment_method=None):
        """更新订单状态"""
        table_name = get_order_table_name(order_id)
        now = timezone.now().strftime('%Y-%m-%d %H:%M:%S')
        
        update_fields = ["status = %s", "updated_at = %s"]
        params = [status, now]
        
        if payment_method:
            update_fields.append("payment_method = %s")
            update_fields.append("payment_time = %s")
            params.extend([payment_method, now])
        
        params.append(order_id)  # WHERE条件参数
        
        with connection.cursor() as cursor:
            query = f"UPDATE {table_name} SET {', '.join(update_fields)} WHERE id = %s"
            cursor.execute(query, params)
            return cursor.rowcount > 0  # 返回是否更新成功
    
    @staticmethod
    def get_orders_by_appointment(appointment_id):
        """根据预约ID查询订单"""
        orders = []
        
        for i in range(3):  # 查询三个分表
            table_name = f"reservation_order_{i}"
            
            with connection.cursor() as cursor:
                cursor.execute(
                    f"SELECT * FROM {table_name} WHERE appointment_id = %s",
                    [appointment_id]
                )
                rows = cursor.fetchall()
                
                for row in rows:
                    # 列名和位置
                    columns = ['id', 'order_number', 'patient_id', 'doctor_id', 
                              'appointment_id', 'amount', 'status', 'payment_method', 
                              'payment_time', 'created_at', 'updated_at']
                    
                    # 构建结果字典
                    result = {}
                    for i, column in enumerate(columns):
                        if i < len(row):
                            result[column] = row[i]
                    
                    orders.append(result)
        
        return orders

    @staticmethod
    def get_order_by_order_number(order_number):
        """根据订单号查询订单"""
        for i in range(3):  # 查询三个分表
            table_name = f"reservation_order_{i}"
            
            with connection.cursor() as cursor:
                cursor.execute(
                    f"SELECT * FROM {table_name} WHERE order_number = %s",
                    [order_number]
                )
                row = cursor.fetchone()
                
                if row:
                    # 列名和位置
                    columns = ['id', 'order_number', 'patient_id', 'doctor_id', 
                              'appointment_id', 'amount', 'status', 'payment_method', 
                              'payment_time', 'created_at', 'updated_at']
                    
                    # 构建结果字典
                    result = {}
                    for i, column in enumerate(columns):
                        if i < len(row):
                            result[column] = row[i]
                    
                    return result
        
        return None

    @staticmethod
    def delete_order(order_id):
        """物理删除订单"""
        table_name = get_order_table_name(order_id)
        
        with connection.cursor() as cursor:
            cursor.execute(
                f"DELETE FROM {table_name} WHERE id = %s",
                [order_id]
            )
            return cursor.rowcount > 0  # 返回是否删除成功



